package tech.hdis.framework.utils.spring;

import lombok.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

/**
 * spring工具包。
 * 用于普通类调用spring容器内对象。
 * 可以当做静态方法调用。
 *
 * @author 黄志文
 */
@Component("serviceSpringUtils")
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 根据注解获取Spring容器内对象
     *
     * @param clazz 注解Class
     * @return 对象列表
     */
    public static List<Object> getBeanNamesForAnnotation(@NonNull Class<? extends Annotation> clazz) {
        String[] beanNamesForAnnotation = applicationContext.getBeanNamesForAnnotation(clazz);
        List<Object> objectList = new ArrayList<>();
        for (String beanName : beanNamesForAnnotation) {
            objectList.add(applicationContext.getBean(beanName));
        }
        return objectList;
    }

    /**
     * 根据对象名称获取Spring容器内对象
     *
     * @param beanName 类名
     * @return 对象
     */
    public static Object getBeanByName(@NonNull String beanName) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(beanName);
    }

    /**
     * 根据对象名称获取Spring容器内对象
     *
     * @param clazz 类Class
     * @return 对象
     */
    public static Object getBeanByClass(@NonNull Class clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }
}